/**
 * 
 */
package cn.edu.cqu.bysj.wm.neo4j;

import java.io.File;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.Transaction;
import org.neo4j.kernel.EmbeddedGraphDatabase;
import org.neo4j.tooling.GlobalGraphOperations;

import cn.edu.cqu.bysj.wm.util.DeleteDirectory;


/**
 * 
 * @author Meng
 * 
 *         Neo4j grapth data base service
 */
public class Neo4jGraphDb {

	public GraphDatabaseService db;
	private String dbPath;

	/**
	 * @param dbPath
	 */
	public Neo4jGraphDb(String dbPath) {
		this.dbPath = dbPath;
		createDb(dbPath);
	}
	/**
	 * open the graph database
	 * @param dbPath
	 * @return
	 */
	public GraphDatabaseService openDb(String dbPath){
		db = new EmbeddedGraphDatabase(dbPath);
		registerShutdownHook(db);
		return db;
	}
	
	/**
	 * create graph database
	 * 
	 * @param dbPath
	 */
	public void createDb(String dbPath) {
		deleteDb();
		System.out.println("-------------------------------------------creating the database--------------------------------------------------------------------------------------");
		db = new EmbeddedGraphDatabase(dbPath);
		registerShutdownHook(db);
	}

	/**
	 * delete grapth database
	 */
	public void deleteDb() {
		System.out.println("-------------------------------------------deleting the database--------------------------------------------------------------------------------------");
		DeleteDirectory.deleteDirectory(new File(dbPath));
	}

	/**
	 * clear database, but the id can not back to 1
	 */
	public void clearDb() {
		Transaction tx = db.beginTx();
		try {

			System.out.println("clearing the database...");
			for (Relationship rel : GlobalGraphOperations.at(db)
					.getAllRelationships()) {
				rel.delete();
			}
			for (Node node : GlobalGraphOperations.at(db).getAllNodes()) {
				if (node.getId() != 0)
					node.delete();
			}

			tx.success();
		} finally {
			tx.finish();
		}
	}

	/**
	 * shut down database
	 */
	public void shutDownDb() {
		System.out.println("-------------------------------------------shutting down the database--------------------------------------------------------------------------------------\n");
		db.shutdown();
	}

	private static void registerShutdownHook(final GraphDatabaseService gdb) {
		// Registers a shutdown hook for the Neo4j instance so that it
		// shuts down nicely when the VM exits (even if you "Ctrl-C" the
		// running example before it's completed)
		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				gdb.shutdown();
			}
		});
	}
}